package com.margiel.util;

import java.io.File;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import com.margiel.rozkladowka.costs.ConnectionType;

public class FileUtil {
	public static File getFolder(File file) {
		if (file.isFile()) {
			return file.getParentFile();
			
		} else {
			String link = file.getPath();
			if (!link.endsWith(File.separator)){
				link+=File.separator;
			}
			return new File(link);
		}
	}
	
	public static String getFileLink(String... links){
		List<String> linksList =  Arrays.asList(links);
		File f = null;
		for (Iterator<String> iterator = linksList.iterator(); iterator.hasNext();) {
			String link = (String) iterator.next();
			if (f== null){
				f = new File(link);
			}else{
				f = new File(getFolderLink(f)+link);
			}
			if (iterator.hasNext()){
				f = getFolder(f);
			}
			
		}
		return f.getAbsolutePath();
	}
	public static String getURLLink(String... links) {
		String linkString = "";
		List<String> linksList = Arrays.asList(links);
		for (Iterator<String> iterator = linksList.iterator(); iterator.hasNext();) {
			String link = (String) iterator.next();
			linkString += link;
			if (iterator.hasNext()) {
				int idx = linkString.lastIndexOf("/");
				if (idx >= 0 && idx < (linkString.length() - 1)) {
					linkString = linkString.substring(0, idx+1);
				}
			}
		}
		return linkString;
	}
	public static String getFolderLink(File file){
		file = getFolder(file);
		String link = file.getPath();
		if (!link.endsWith(File.separator)){
			link+=File.separator;
		}
		return link;
	}
	public static String getLink(ConnectionType connectionType, String... links){
		switch (connectionType) {
		case FILE:
			return getFileLink(links);
		case URL:
			return getURLLink(links);
		default:
			return null;
		}
	}
}
